# -*- coding: utf-8 -*-
# owner: shenyi

# src/core/middleware.py

import time
from fastapi import Request
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from . import ApiResponse, logger

def register_middlewares(app):
    # 添加 CORS 中间件
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # 请求耗时中间件
    @app.middleware("http")
    async def add_process_time_header(request: Request, call_next):
        start_time = time.time()
        response = await call_next(request)
        process_time = (time.time() - start_time) * 1000  # 转换为毫秒
        response.headers["X-Process-Time"] = f"{process_time:.2f} ms"
        return response

    # 全局异常处理中间件
    @app.middleware("http")
    async def exception_handler_middleware(request: Request, call_next):
        try:
            return await call_next(request)
        except Exception as e:
            logger().exception("Unhandled exception occurred")
            return JSONResponse(
                status_code=500,
                content=ApiResponse(code=500, message="Internal Server Error", data=str(e)).dict()
            )